package com.cqvip.innocence.framework.config.elasticsearch;

import cn.hutool.core.util.StrUtil;
import com.cqvip.innocence.common.exception.ElasticServiceException;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @ClassName ElasticSearchClientConfig
 * @Description yml形式配置es的超时无效，因此用配置类的形式进行相关配置
 * @Author Innocence
 * @Date 2021/4/9 14:07
 * @Version 1.0
 */
@Configuration
public class ElasticSearchClientConfig {

    @Value("${elasticsearch.url}")
    private String url;

    @Value("${elasticsearch.connect-timeout}")
    private Integer connectTimeout;

    @Value("${elasticsearch.socket-timeout}")
    private Integer socketTimeout;

    @Bean
    @Qualifier("highLevelClient")
    public RestHighLevelClient restHighLevelClient() {
        // 该方法接收一个RequestConfig.Builder对象，对该对象进行修改后然后返回。
        RestHighLevelClient highLevelClient = new RestHighLevelClient(
                RestClient.builder(getHosts(url))
                        .setRequestConfigCallback(requestConfigBuilder -> {
                            return requestConfigBuilder.setConnectTimeout(connectTimeout) // 连接超时（默认为1秒）
                                    .setSocketTimeout(socketTimeout);// 套接字超时（默认为30秒）//更改客户端的超时限制默认30秒现在改为100*1000分钟
                        }));
        // 调整最大重试超时时间（7.9.2版本没有这个API 默认为30秒）.setMaxRetryTimeoutMillis(60000);
        return highLevelClient;
    }

    private HttpHost[] getHosts(String url) {
        final boolean blank = StrUtil.isBlank(url);
        if (blank) {
            throw new ElasticServiceException("elasticsearch host must not be null!");
        }
        if (url.indexOf(",") == -1) {
            return new HttpHost[]{HttpHost.create(url)};
        }
        CopyOnWriteArrayList<HttpHost> httpHosts = new CopyOnWriteArrayList<>();
        for (String s : url.split(",")) {
            httpHosts.add(HttpHost.create(s));
        }
        return httpHosts.toArray(new HttpHost[]{});
    }
}
